package com.flame.system.log.service;

import java.util.List;

import com.flame.auth.core.event.LoginEvent;
import com.flame.core.id.IdWorker;
import com.flame.core.utils.DateUtils;
import com.flame.core.utils.HttpUtils;
import com.flame.system.log.controller.vo.UserLoginLogVo;
import com.flame.system.log.entity.UserLoginLog;
import com.flame.system.log.mapper.UserLoginLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * flame_user_login_log 登录日志表
 *
 * @author 吴欣童
 * @since 2023-02-23 18:22:33
 */
@Service
public class UserLoginLogService {

    @Autowired
    private UserLoginLogMapper userLoginLogMapper;

    @Autowired
    private IdWorker idWorker;

    public List<UserLoginLog> pageUserLoginLog(UserLoginLogVo userLoginLogVo) {
        return userLoginLogMapper.page(userLoginLogVo);
    }

    @Async
    @EventListener
    public void loginEventHandler(LoginEvent loginEvent) {
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setLogId(idWorker.nextId());
        userLoginLog.setUserId(loginEvent.getUserId());
        userLoginLog.setLoginStatus(loginEvent.getLoginStatus());
        userLoginLog.setLoginTime(DateUtils.formatedDateTime(loginEvent.getTimestamp()));
        String[] userAgentInfo = HttpUtils.getBrowserInfoAndOperatingSystemInfo(loginEvent.getUserAgent());
        userLoginLog.setBrowserInfo(userAgentInfo[0]);
        userLoginLog.setOperatingSystemInfo(userAgentInfo[1]);
        userLoginLog.setIp(loginEvent.getIp());
        userLoginLog.setAddress(HttpUtils.getAddress(loginEvent.getIp()));
        userLoginLogMapper.insert(userLoginLog);
    }

    public void batchDelete(List<Long> logIdList) {
        userLoginLogMapper.batchDelete(logIdList);
    }

    public void clear() {
        userLoginLogMapper.clear();
    }
}
